package com.example.lotterysystem.controller;

import com.example.lotterysystem.common.poji.CommonResult;
import com.example.lotterysystem.common.utils.JacksonUtil;
import com.example.lotterysystem.controller.param.DrawPrizeParam;
import com.example.lotterysystem.controller.param.ShowWinningRecordsParam;
import com.example.lotterysystem.controller.result.WinningRecordResult;
import com.example.lotterysystem.service.DrawPrizeService;
import com.example.lotterysystem.service.dto.WinnerRecordDTO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@RestController
public class DrawPrizeController {

    private static final Logger logger = LoggerFactory.getLogger(DrawPrizeController.class);

    @Autowired
    DrawPrizeService drawPrizeService;

    @RequestMapping("/draw-prize")
    public CommonResult<Boolean> drawPrize(@Validated @RequestBody DrawPrizeParam param) {
        logger.info("drawPrize DrawPrizeParam:{}", JacksonUtil.writeValueAsString(param));
        // service
        drawPrizeService.drawPrize(param);
        return CommonResult.success(true);
    }

    @RequestMapping("winning-records/show")
    public CommonResult<List<WinningRecordResult>> ShowWinningRecords(@Validated @RequestBody ShowWinningRecordsParam param) {
        logger.info("ShowWinningRecords ShowWinningRecordsParam:{}", JacksonUtil.writeValueAsString(param));
        List<WinnerRecordDTO> winnerRecordDTOList =  drawPrizeService.getRecords(param);
        return CommonResult.success(convertToWinnerRecordDTOList(winnerRecordDTOList));
    }

    private List<WinningRecordResult> convertToWinnerRecordDTOList(List<WinnerRecordDTO> winnerRecordDTOList) {
        if(CollectionUtils.isEmpty(winnerRecordDTOList)) {
            return Arrays.asList();
        }
        return winnerRecordDTOList.stream()
                .map(winnerRecordDTO -> {
                    WinningRecordResult result = new WinningRecordResult();
                    result.setWinnerId(winnerRecordDTO.getWinnerId());
                    result.setWinnerName(winnerRecordDTO.getWinnerName());
                    result.setPrizeName(winnerRecordDTO.getPrizeName());
                    result.setPrizeTier(winnerRecordDTO.getPrizeTier().getMessage());
                    result.setWinningTime(winnerRecordDTO.getWinnerTime());
                    return result;
                }).collect(Collectors.toList());
    }
}
